<?php

class Login extends M_Controller
{
    /**
     * 账密登录 ['username','phone']
     *code=3 并未更改初始密码
     */
    public function accountLogin()
    {
        try {
            if (empty($_POST['password'])) {
                throw new Exception('请输入密码', 1);
            }
            if (!$_POST['username'] && !$_POST['phone']) {
                throw new Exception('登录方式错误', 1);
            }
            $memberInfo = $this->models('member')->fieldInfo('username', $_POST['phone']);
            if (empty($memberInfo)) {
                throw new Exception('账户不存在', 1);
            }
            $password = trim($_POST['password']);
            if (md5(md5($password) . $memberInfo['salt'] . md5($password)) != $memberInfo['password']) {
                throw new Exception('密码不正确', 1);
            }
            if ($memberInfo['uid'] == 18) {
                x_json(1,
                    [
                        'uid' => $memberInfo['uid'],
                        'overdue' => SYS_TIME + 86400,
                        'token' => 'b1f4251bc88ae5bb245add4a2ae22b96',
                        'sign' => 'f08fc318f17fe8f5ffca6f80a5cbe648'
                    ], '测试账号登录成功');
            } else {
                $info = $this->clientType($memberInfo['uid'], $memberInfo['password']);
                if (empty($info)) {
                    throw  new Exception('登录失败', 1);
                }
                $this->loginAfter($memberInfo['uid']);
                x_json(1, $info, '登录成功');
            }

        } catch (Exception $e) {
            x_json(0, $e->getMessage(), false);
        }

    }

    /**
     *短信登录&& 登录
     * code=3 并未更改初始密码
     */
    public function codeLogin()
    {
        try {
            if (empty($_POST['phone'])) {
                throw  new Exception('请输入手机号', 1);
            }
            $code = $this->models('system/sms')->getCaptcha($_POST['phone'], 'register');
            if (empty($code)) {
                throw  new Exception('验证码不存在', 1);
            }
            if ($code != $_POST['code']) {
                throw  new Exception('验证码不正确', 1);
            }
            $memberInfo = $this->models('member')->fieldInfo('username', $_POST['phone']);
            if (empty($memberInfo)) {
                ###用户不存在,注册用户
                $data = [
                    'password' => '123456',
                    'username' => trim($_POST['phone']),
                    'phone' => trim($_POST['phone'])
                ];
                $this->models('member/register')->add($data);
                $memberInfo = $this->models('member')->fieldInfo('username', $_POST['phone']);
            }
            $info = $this->clientType($memberInfo['uid'], $memberInfo['password']);
            if (empty($info)) {
                throw  new Exception('登录失败', 1);
            }
            $this->loginAfter($memberInfo['uid']);
            $this->models('system/sms')->deleteCaptcha(trim($_POST['phone']), 'register');
            ### 判断是否设置密码
            $status = $this->psdStatus($memberInfo['password'], $memberInfo['salt']);
            x_json($status, ['uid'=>$info], '登录成功');
        } catch (Exception $e) {
            x_json(0, $e->getMessage(), false);
        }

    }

    //忘记密码
    public function forgetPassword()
    {
        try {
            if (empty($_POST['phone'])) {
                throw  new Exception('手机号不存在', 1);
            }
            $code = $this->models('system/sms')->getCaptcha(trim($_POST['phone']), 'change_password');
            if (empty($code)) {
                throw  new Exception('验证码不存在', 1);
            }
            if (trim($_POST['password']) !== trim($_POST['new_psd'])) {
                throw  new Exception('两次密码不一致', 1);
            }
            $memberInfo = $this->models('member')->fieldInfo('username',$_POST['phone']);
            if (empty($memberInfo)) {
                throw  new Exception('用户不存在', 1);
            }
            ### 更新密码
            $data = [
                'password' => md5(md5(trim($_POST['password'])) . $memberInfo['salt'] . md5(trim($_POST['password']))),
            ];
            $affectRow = $this->models('member')->updateMember($data, $memberInfo['uid']);
            if ($affectRow < 0) {
                throw  new Exception('修改失败', 1);
            }
            $this->models('system/sms')->deleteCaptcha($_POST['phone'], 'change_password');
            $info = $this->clientType($memberInfo['uid'], trim($_POST['password']));
            if (empty($info)) {
                throw  new Exception('登录失败', 1);
            }
            x_json(1, ['uid'=>$info], '修改成功');
        } catch (Exception $e) {
            x_json(0, $e->getMessage(), false);
        }

    }

    // 修改密码
    public function changePassword()
    {
        try {
            if (empty($this->uid)) {
                throw new Exception('请登录', 2);
            }
            $memberInfo = $this->models('member')->uidInfo($this->uid, 'uid,password,salt');
            if (empty($memberInfo)) {
                throw new Exception('用户信息不存在', 1);
            }
            $password = trim($_POST['password']);
            $newPassword = trim($_POST['new_password']);
            if ($password != $newPassword) {
                throw  new Exception('两次密码不一致', 1);
            }
            if (md5(md5($password) . $memberInfo['salt'] . md5($password)) == $memberInfo['password']) {
                throw new Exception('修改密码与原密码相同', 1);
            }
            $data = [
                'password' => md5(md5(trim($newPassword)) . $memberInfo['salt'] . md5(trim($newPassword))),
            ];
            $affectRow = $this->models('member')->updateMember($data, $memberInfo['uid']);
            if ($affectRow < 0) {
                throw  new Exception('修改失败', 1);
            }
            $info = $this->clientType($memberInfo['uid'], $newPassword);
            x_json(1, $info, '修改成功');
        } catch (Exception $e) {
            if ($e->getCode() == 2) {
                x_json(-4001, $e->getMessage(), false);
            }
            x_json(0, $e->getMessage(), false);
        }


    }

    /**
     * 判断手机或者电脑
     * @param $uid
     * @param $password
     * @return bool
     */
    private function clientType($uid, $password)
    {
        if (empty($uid) || empty($password)) {
            return false;
        }
        $type = is_mobile() ? 'MOBILE' : 'PC';
        switch ($type) {
            case 'MOBILE' :
                return $this->models('member/login')->authcode($uid);
                break;
            case 'PC' :
                $this->input->set_cookie('member_uid', $uid, 86400);
                $this->input->set_cookie('member_cookie', substr(md5(SYS_KEY . $password), 5, 20), 86400);
                return $uid;
                break;
            default:
                return false;
        }
    }

    /**
     * 检查是否设置密码
     * @param $password
     * @param $salt
     * @return int
     */
    private function psdStatus($password, $salt)
    {
        if (empty($password) || empty($salt)) {
            return 0;
        }
        $psd = md5(md5('123456') . $salt . md5('123456'));
        if ($psd === $password) {
            return 3;
        } else {
            return 1;
        }
    }

    // 更新用户clientID
    public function clientUser()
    {
        if (empty($this->uid)) {
            x_json(-4001, '请登录');
        }
        if (empty($_GET['client'])) {
            x_json(0, '参数缺失');
        }
        if ($this->models('message')->updateClient($_GET['client'], $this->uid)) {
            x_json(1, 'yes');
        } else {
            x_json(0, 'no');
        }
    }

    ### 增加登录时间和登录次数
    private function loginAfter($uid)
    {
        if (empty($uid)) {
            return false;
        }
        $this->models('member')->updateMember(['login_time' => SYS_TIME], $uid);
        $this->models('member')->addNums('login_nums', '1', $uid);
    }

    // ap 端扫码登录
    public function scanLogin()
    {
        if (empty($_GET['token'])) {
            x_json(0, '令牌缺失');
        }
        if (empty($token = $this->models('member/login')->scanUid($_GET['token']))) {
            x_json(0, '无效令牌');
        }
        if ($token['overdue'] < SYS_TIME) {
            x_json(0, '令牌已过期, 请重试');
        }
        x_json(1, ['type' => 'login', 'token' => $token['sign'], 'id' => $token['id']], '成功扫码');
    }

    // ap 扫码绑定
    public function bindToken()
    {
        try {
            if (empty($this->uid)) {
                x_json(-4001, '请登录');
            }
            if (empty($_GET['token'])) {
                throw new Exception('无效令牌');
            }
            if (empty($token = $this->models('member/login')->scanUid($_GET['token']))) {
                throw new Exception('无效令牌');
            }
            if ($token['overdue'] < SYS_TIME) {
                throw new Exception('令牌已过期, 请重试');
            }
            $memberInfo = $this->models('member')->uidInfo($this->uid, 'uid');
            if (empty($memberInfo)) {
                throw new Exception('用户不存在');
            }
            if (empty($this->models('member/login')->updateScan($token['id'], $memberInfo['uid']))) {
                throw new Exception('绑定令牌失败');
            }
            x_json(1, ['uid' => $memberInfo['uid'], 'status' => 'scan'], '等待确认登录');
        } catch (Exception $e) {
            x_json(0, $e->getMessage());
        }

    }

    // PC轮询用令牌获取用户
    public function scanPoll()
    {
        try {
            if (empty($_GET['token'])) {
                throw new Exception('登录令牌缺失');
            }
            $signInfo = $this->models('member/login')->scanUid($_GET['token']);
            if (empty($signInfo)) {
                throw new Exception('暂无查询到令牌对应的用户,请重试');
            }
            if ($signInfo['overdue'] < SYS_TIME) {
                x_json(1, ['status' => 'expired'], '令牌已过期, 请重试');
            }
            if (!empty($signInfo['uid'])) {
                $member = $this->models('member')->uidInfo($signInfo['uid'], 'uid,password');
                if (empty($member)) {
                    throw new Exception('用户信息错误,请重试');
                }
                $this->input->set_cookie('member_uid', $member['uid'], 86400);
                $this->input->set_cookie('member_cookie', substr(md5(SYS_KEY . $member['password']), 5, 20), 86400);
                $this->loginAfter($member['uid']);
                $this->models('member/login')->deleteCode($signInfo['id']);
                x_json(1, ['uid' => $member['uid'], 'status' => 'login'], '成功登录');
            }
            $this->models('member/login')->delToken();
            x_json(1, ['status' => 'waiting'], 'success');
        } catch (Exception $e) {
            x_json(0, $e->getMessage());
        }
    }

    public function loginCode()
    {
        $token = md5(substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . date('s'));
        if (empty($this->models('member/login')->scanLogin([
            'overdue' => SYS_TIME + 60,
            'sign' => $token
        ]))) {
            x_json(0, '生成二维码参数错误,请重试');
        }
        x_json(1, [
            'url' => dr_qrcode_url(SITE_URL . '/index.php?c=login&m=scanLogin&token=' . $token),
            'token' => $token,
            'status' => 'start'
        ], '已生成二维码');
    }

    // 删除令牌
    public function delToken()
    {
        if (empty($_GET['id'])) {
            return false;
        }
        return $this->models('member/login')->deleteCode($_GET['id']);
    }
}